package com.gofaraway.service.student.leetcode;

import com.alibaba.fastjson.JSON;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * @author ChenPeng
 * @Date 2024/9/12 22:30
 */
public class Demo10 {


    /**
     * 二叉树的右视图:
     * 给定一个二叉树的 根节点 root，想象自己站在它的右侧，按照从顶部到底部的顺序，返回从右侧所能看到的节点值。
     *
     * @param root
     * @return
     */
    public List<Integer> rightSideView(TreeNode root) {

        ArrayList<Integer> list = new ArrayList<>();

        HashMap<Integer, List<Integer>> levelMap = new HashMap<>();

        levelMap.put(0, Arrays.asList(root.val));
        handler(root, levelMap, 1);

        levelMap.forEach((k, v) -> {
            List<Integer> integers = levelMap.get(k);
            if (integers == null || integers.size() == 0) {
                return;
            }
            list.add(integers.get(integers.size() -1));
        });
        return list;

    }

    private void handler(TreeNode root, HashMap<Integer, List<Integer>> levelMap, int level) {
        if (root == null) return;
        List<Integer> currList = levelMap.get(level) == null ? new ArrayList<>() : levelMap.get(level);
        if (root.left != null) {
            currList.add(root.left.val);
            levelMap.put(level, currList);
            handler(root.left, levelMap, level+1);
        }

        if (root.right != null) {
            currList.add(root.right.val);
            levelMap.put(level, currList);
            handler(root.right, levelMap, level+1);
        }
    }


    public List<Integer> rightSideViewV2(TreeNode root) {
        ArrayList<Integer> list = new ArrayList<>();
        handlerV2(root, list, 0);
        return list;
    }

    private void handlerV2(TreeNode root,  ArrayList<Integer> list, int level) {
        if (root == null) return;
        if (list.size() == level) {
            list.add(root.val);
        }
        if (root.left != null) {
            handlerV2(root.left, list, level+1);
        }
        if (root.right != null) {
            handlerV2(root.right, list, level+1);
        }
    }

    public static void main(String[] args) {
        ArrayList<Object> objects = new ArrayList<>();
        objects.add(1, 0);
        objects.add(2, 100);

        System.out.println(JSON.toJSONString(objects));
    }



    public class TreeNode {
        public int val;
        public TreeNode left;
        public TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
